﻿using NPOI.Util.ArrayExtensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using TlToolBase;
using TlToolBase.Mode;

namespace TlToolCordCreate
{
    /// <summary>
    /// updataPro.xaml 的交互逻辑
    /// </summary>
    public partial class updataPro : UserControl
    {
        UpdataProModel updataProModel { get; set; }
        public updataPro()
        {
            InitializeComponent();
            updataProModel = FileDataClass.Get<UpdataProModel>();
            if (updataProModel.modelItmes==null)
            {
                updataProModel.modelItmes = new List<UpdataProModelItme>();
            }
            if (updataProModel.modelItmes.Count==0)
            {
                updataProModel.modelItmes.Add(new UpdataProModelItme());
            }
            this.Loaded += UpdataPro_Loaded;

        }

        private void UpdataPro_Loaded(object sender, RoutedEventArgs e)
        {
            LocaItem();
        }
        private void LocaItem()
        {
            ui.Children.Clear();
            foreach (var item in updataProModel.modelItmes)
            {
                RadioButton cb = new ();
                cb.Tag = item;
                cb.Content = item.itemkey;
                cb.Checked += Cb_Checked;
                ui.Children.Add(cb);
            }
          
        }

        private void Cb_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rad = sender as RadioButton;
            UpdataProModelItme item = rad.Tag as UpdataProModelItme;
            soupath.Text = item.souPath;
            dstpath.Text = item.dstPath;
            startPro.Text = item.startPro;
            key.Text = item.itemkey;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            mess.Content = "文件更新";
            if (string.IsNullOrEmpty(key.Text))
            {
                mess.Content = "启动名称不为空";
                return;
            }
            var it= updataProModel.modelItmes.Find(x => x.itemkey == key.Text);
            if (it == null)
            {
                it = new UpdataProModelItme()
                {
                    souPath = soupath.Text,
                    dstPath = dstpath.Text,
                    startPro = startPro.Text,
                    itemkey= key.Text
                };
                updataProModel.modelItmes.Add(it);
            }
          
            FileDataClass.Save(updataProModel);
            var sou = Directory.GetFiles(soupath.Text);
            var dst = Directory.GetFiles(dstpath.Text);
            try
            {
                foreach (var file in sou)
                {
                    FileInfo soufileInfo = new FileInfo(file);
                    FileInfo dstfileInfo = null;
                    var soupath = Path.GetFileName(file);
                    if (updataProModel.ignore.Contains(soupath))
                    {
                        continue;
                    }
                    foreach (var item in dst)
                    {
                        var dstpath = Path.GetFileName(item);
                        if (soupath == dstpath)
                        {
                            dstfileInfo = new FileInfo(item);
                        }
                    }
                    if (dstfileInfo == null)
                    {
                        soufileInfo.CopyTo(dstpath.Text + "\\" + soupath);
                    }
                    else
                    {
                        if (soufileInfo.LastWriteTime != dstfileInfo.LastWriteTime)
                        {
                            soufileInfo.CopyTo(dstpath.Text + "\\" + soupath, true);
                        }
                    }
                }
            }
            catch (Exception EX)
            {
                MessageBox.Show(EX.Message);
            }
            mess.Content = "更新完成";
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            mess.Content = "程序启动";
            try
            { // 调用
                string filepath = dstpath.Text + "\\" + startPro.Text;
                //IntPtr result = ShellExecute(IntPtr.Zero, "open", filepath, "", "", 3);
                // StartFun1(filepath);
                StartFun2(filepath);
            }
            catch
            {

            }
        }
        private void StartFun1(string path)
        {
            WinExec(path, 3);
        }
        private void StartFun2(string path)
        {
            ProcessStartInfo process = new();

            process.FileName = path;

            process.WorkingDirectory = dstpath.Text;
            int type = 1;
            if (type == 2)
            {
                //无窗口
                process.CreateNoWindow = true;
                process.UseShellExecute = false;
            }
            else
            {
                process.CreateNoWindow = false;
                process.UseShellExecute = true;
            }
            Process.Start(process);
        }
        /// <summary>
        /// 
        /// </summary>
        private void StartPro()
        {
            mess.Content = "杀进程";
            Task.Factory.StartNew(() =>
            {
                this.Dispatcher.Invoke(new Action(() => {
                    var pro = Finprs();
                    if (pro != null)
                    {
                        pro.Kill();
                    }
                }));
                Thread.Sleep(100);
                this.Dispatcher.Invoke(new Action(() => {
                    Button_Click(null, null);
                }));
                Thread.Sleep(100);
                bool flag = true;
                while (flag)
                {
                    this.Dispatcher.Invoke(new Action(() => {
                        if (mess.Content == "更新完成")
                        {
                            Button_Click_1(null, null);
                            flag=false;
                        }
                    }));
                    Thread.Sleep(100);
                }
              
            });
        }
        private Process Finprs()
        {
            var pro = Process.GetProcesses();
            string name = startPro.Text;
            name = name.Replace(".exe", "");
            foreach (var proc in pro)
            {
                Console.WriteLine(proc.ProcessName);
                if (proc.ProcessName == name)
                {
                    return proc;
                }
            }
            return null;
        }
        // 引入库
        [DllImport("shell32.dll")]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

        [DllImport("kernel32.dll")]
        public static extern int WinExec(string programPath, int operType);



        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            mess.Content = "杀进程";
            var pro = Process.GetProcesses();

            string name = startPro.Text;
            name = name.Replace(".exe","");
            foreach (var proc in pro)
            {
                Console.WriteLine(proc.ProcessName);
                if (proc.ProcessName== name)
                {
                    proc.Kill();
                }
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            StartPro();
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            OpenFolder(dstpath.Text);
        }
        /// <summary>
        /// 打开目录
        /// </summary>
        /// <param name="folderPath">目录路径（比如：C:\Users\Administrator\）</param>
        private static void OpenFolder(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath)) return;

            Process process = new Process();
            ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
            psi.Arguments = folderPath;
            process.StartInfo = psi;

            try
            {
                process.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                process?.Close();

            }

        }

    }
}
